const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// css文件压缩处理
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin')

module.exports = {
  target: "web",
  entry: {
    main:'./src/js/index.js',
    print:'./src/js/print.js'
  },
  output: {
    filename: 'js/[name].[contenthash:5].js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      // loader的配置
      {
        // 处理css资源
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            // 还需要在package.json中定义browserslist
            loader: 'postcss-loader',
            options: {
              'postcssOptions':{
                plugins:['postcss-preset-env']
              }
            }
          }
        ]
      },
      {
        test: /\.js$/,
        include: [
          resolve(__dirname, './src')
        ],
        loader: 'babel-loader',
        options: {
          // 预设：指示babel做怎么样的兼容性处理
          presets: [
            [
              '@babel/preset-env',
              {
                // 按需加载
                useBuiltIns: 'usage',
                // 指定core-js版本
                corejs: {
                  version: 3
                },
                // 指定兼容性做到哪个版本浏览器
                targets: {
                  chrome: '60',
                  firefox: '60',
                  ie: '9',
                  safari: '10',
                  edge: '17'
                }
              }
            ]
          ],
          // 开启babel缓存
          // 第二次构建时，会读取之前的缓存
          // cacheDirectory: true
        }
      },
      {
        // 处理html中img资源
        test: /\.html$/,
        loader: 'html-loader'
      },
    ]
  },
  plugins: [
    // plugins的配置
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
      filename:'css/[name].[contenthash:5].css'
    }),
    // css压缩
    new CssMinimizerWebpackPlugin()
  ],
  mode: 'production',
  devServer: {
    compress: true,
    port: 3000,
    open: true,
    // 开启HMR功能
    // 当修改了webpack配置，新配置要想生效，必须重新webpack服务
    hot: true
  }
};